import React, { useState } from 'react';
import { View, router, Text, getDeviceProperty, setDeviceProperty, hideMenuButton } from '@ray-js/ray';
import { useActions, useProps } from '@ray-js/panel-sdk';
import { useSelector, useDispatch } from 'react-redux';
import { NavBar, DateTimePicker, Radio, RadioGroup, Field, Cell, CellGroup, Popup } from '@ray-js/smart-ui';
import styles from './index.module.less';
import { selectSystemInfoByKey } from '@/redux/modules/systemInfoSlice';
import { WeekSelect } from '@/components';
import { showToastHandle, getDevId, isAllZeros, toTwoHex, hexToDecimal, hexToDecimalTwo, judgingConflicts, sprintf } from '@/utils';
import Strings from '@/i18n';
import { TopBar, TimePicker } from '@/components';
import { getRunMin, getRunSecond } from '@/constant';


export default function Addtimer(props) {
  hideMenuButton()
  const actions = useActions();
  const dispatch = useDispatch();


  const order = Number(props.location.query.order) //0 | 1，2，3，4...
  const dpValue = props.location.query.dpValue

  console.log("order", order, "dpValue", dpValue);
  const now = new Date();
  const startDefHm = now.getHours() + ":" + now.getMinutes();
  now.setMinutes(now.getMinutes() + 2);
  //  const hours = String(now.getHours()).padStart(2, '0');
  // const minutes = String(now.getMinutes()).padStart(2, '0');


  const endDefHm = now.getHours() + ":" + now.getMinutes();
  const [startTimeValue, setStartTimeValue] = React.useState(!isAllZeros(dpValue) ? hexToDecimalTwo(dpValue.slice(4, 6)) + ":" + hexToDecimalTwo(dpValue.slice(6, 8)) : startDefHm); //startTime
  const [endTimeValue, setEndTimeValue] = React.useState(!isAllZeros(dpValue) ? hexToDecimalTwo(dpValue.slice(8, 10)) + ":" + hexToDecimalTwo(dpValue.slice(10, 12)) : endDefHm); //endTime

  const [runTime, setRunTime] = React.useState(!isAllZeros(dpValue) ? hexToDecimal(dpValue.slice(12, 14)) + ":" + hexToDecimalTwo(dpValue.slice(14, 16)) : "00:05"); //endTime
  const [pauseTime, setPauseTime] = React.useState(!isAllZeros(dpValue) ? hexToDecimal(dpValue.slice(16, 18)) + ":" + hexToDecimalTwo(dpValue.slice(18, 20)) : "00:05"); //startTime

  const [loops, setLoops] = React.useState(!isAllZeros(dpValue) ? parseInt(dpValue.slice(2, 4), 16).toString(2).padStart(7, '0') : "0000000") //loops


  const timer_1 = useProps(props => props.timer_1)
  const timer_2 = useProps(props => props.timer_2)
  const timer_3 = useProps(props => props.timer_3)
  const timer_4 = useProps(props => props.timer_4)
  const timer_5 = useProps(props => props.timer_5)

  const timerArr = [timer_1, timer_2, timer_3, timer_4, timer_5,]



  //开始时间选择框
  /**
   * Handles the change event for the start time picker.
   * @param e - The event object containing selection details
   * @param e.detail - The detail object from the event
   * @param e.detail.value - The selected value from the picker
   * @param e.detail.index - The index of the selected item
   */
  const handleStartPickerChange = (e) => {
    console.log("event", e.detail);
    const { value, index } = e.detail;

    onStartTimeConfirm(value[0] + ":" + value[1])

  }
  //开始时间选择框
  const handleEndPickerChange = (e) => {
    console.log("event", e.detail);
    const { value, index } = e.detail;
    onEndTimeConfirm(value[0] + ":" + value[1])

  }
  //运行时长
  const handleRunPickerChange = (e) => {
    console.log("event", e.detail);
    const { value, index } = e.detail;
    onRunTimeConfirm(value[0] + ":" + value[1])
  }
  //暂停时间
  const handlePausePickerChange = (e) => {
    console.log("event", e.detail);
    const { value, index } = e.detail;
    onPauseTimeConfirm(value[0] + ":" + value[1])

  }


  /**
   * 检查两个时间（"HH:MM"格式）的差值是否 >= 2 分钟
   * @param {string} startTime 开始时间（如 "14:30"）
   * @param {string} endTime 结束时间（如 "14:32"）
   * @returns {boolean} 是否相差 2 分钟以上
   */
  function isTimeDifferenceValid(startTime, endTime) {
    // 1. 解析时间字符串
    const [startHour, startMinute] = startTime.split(':').map(Number);
    const [endHour, endMinute] = endTime.split(':').map(Number);

    // 2. 转换为 Date 对象（同一天）
    const startDate = new Date();
    startDate.setHours(startHour, startMinute, 0, 0);

    const endDate = new Date();
    endDate.setHours(endHour, endMinute, 0, 0);

    // 3. 计算时间差（毫秒）
    const diffMs = endDate - startDate;
    const diffMinutes = diffMs / (1000 * 60); // 转为分钟
    return diffMinutes
  }

  const setLoopsHandle = (loops) => {
    console.log("loops", loops);
    setLoops(loops)

  }

  const onStartTimeConfirm = (time: string) => {

    setStartTimeValue(time);
  }

  const onEndTimeConfirm = (time: string) => {
    setEndTimeValue(time);
  }

  const onRunTimeConfirm = (time: string) => {
    setRunTime(time + "");
    console.log("onRunTimeConfirm time", time);
  }
  const onPauseTimeConfirm = (time: string) => {
    setPauseTime(time + "");
    console.log("onPauseTimeConfirm time", time);

  }
  const formatTime = (value: string) => {
    if (Strings.getLang("str_please_select") != value) {
      return value + Strings.getLang("str_minute_desc");
    }
    return value;
  }


  function mmssToSeconds(timeStr) {
    const [minutes, seconds] = timeStr.split(':').map(Number);
    return minutes * 60 + seconds;
  }
  //保存下发
  const save = () => {
    if (loops === "0000000") {
      showToastHandle(Strings.getLang("str_select_day_week"))
    } else {
      let timeDiff = isTimeDifferenceValid(startTimeValue, endTimeValue);
      if (timeDiff < 2) {
        showToastHandle(Strings.getLang("str_time_difference"))
        return
      }
      let pauseS = mmssToSeconds(pauseTime);
      let runS = mmssToSeconds(runTime);
      if (pauseS < 5) {
        showToastHandle(Strings.getLang("str_pause_tips"))
        return
      }
      if (runS < 5) {
        showToastHandle(Strings.getLang("str_run_tips"))
        return
      }
      // console.log("pauseS", pauseS, "runS", runS);

      if ((pauseS + runS) > (timeDiff * 60)) {
        showToastHandle(Strings.getLang("str_run_difference_tips"))
        return
      }

      //fix
      if (dpValue !== "0") {

        console.log("timerArr", timerArr);
        console.log("dpValue", dpValue);


        const order = timerArr.findIndex(item => item == dpValue)
        let chekcek = judgingConflicts(timerArr, loops, startTimeValue, endTimeValue, order, dpValue !== "0");
        if (!chekcek.r) {
          showToastHandle(sprintf(Strings.getLang("str_mode_conflict"), (order + 1).toString()))
          return
        }
        console.log("order", order);

        let cmd = dpValue.slice(0, 2) + parseInt(loops, 2).toString(16).padStart(2, '0') + toTwoHex(startTimeValue.slice(0, 2)) + toTwoHex(startTimeValue.slice(3))
          + toTwoHex(endTimeValue.slice(0, 2)) + toTwoHex(endTimeValue.slice(3))
          + toTwoHex(runTime.slice(0, 2)) + toTwoHex(runTime.slice(3))
          + toTwoHex(pauseTime.slice(0, 2)) + toTwoHex(pauseTime.slice(3))


        actions[`timer_${order + 1}`].set(cmd);

        router.back()

      } else {
        const order = timerArr.findIndex(item => !item || isAllZeros(item))

        if (order === -1) {
          showToastHandle(Strings.getLang("str_timed_reminder"))
          return
        }
        let chekcek = judgingConflicts(timerArr, loops, startTimeValue, endTimeValue, order, dpValue !== "0");
        if (!chekcek.r) {
          showToastHandle(Strings.getLang("str_mode_conflict"))
          return
        }

        let cmd = '01' + parseInt(loops, 2).toString(16).padStart(2, '0') + toTwoHex(startTimeValue.slice(0, 2)) + toTwoHex(startTimeValue.slice(3))
          + toTwoHex(endTimeValue.slice(0, 2)) + toTwoHex(endTimeValue.slice(3))
          + toTwoHex(runTime.slice(0, 2)) + toTwoHex(runTime.slice(3))
          + toTwoHex(pauseTime.slice(0, 2)) + toTwoHex(pauseTime.slice(3))
        // console.log("order", order, "cmd", cmd);
        actions[`timer_${order + 1}`].set(cmd);
      }
      router.back()
    }

  }


  React.useEffect(() => {
    console.log("🚀", order, startTimeValue, endTimeValue, loops, pauseTime);
  }, [startTimeValue, endTimeValue, loops, pauseTime])

  return (
    <View className={styles.view}>
      <TopBar title={dpValue !== "0" ? Strings.getLang("str_edit_timer") : Strings.getLang("str_add_timer")}></TopBar>
      <View className={styles.week_zone}>
        <Text className={styles.zone_title}>{Strings.getLang("str_week_setting")}</Text>

        <WeekSelect loops={loops} setLoops={setLoopsHandle} />
      </View>
      <View className={styles.addArea} >

        <View className={styles.time_zone}>
          <Text className={styles.zone_title}>{Strings.getLang("str_time_setting")}</Text>
          <View className={styles.pickerLayout}>
            <View className={styles.pickerTimer}>
              <TimePicker pickerwidth={'100%'}
                pickerheight={420}
                fontSize={36}
                indicatorheight={56}
                handlePickerChange={handleStartPickerChange}
                title={Strings.getLang("str_start_time")} current={startTimeValue} />
            </View>
            <View className={styles.pickerTimer}>
              <TimePicker pickerwidth={'100%'}
                pickerheight={420}
                fontSize={36}
                indicatorheight={56}
                handlePickerChange={handleEndPickerChange}
                title={Strings.getLang("str_end_time")} current={endTimeValue} />
            </View>
          </View>
        </View>
        <View className={styles.time_zone}>
          <Text className={styles.zone_title}>{Strings.getLang("str_frequency_setting")}</Text>
          <View className={styles.pickerLayout}>
            <View className={styles.pickerTimer}>
              <TimePicker pickerwidth={'100%'}
                pickerheight={420}
                fontSize={36}
                indicatorheight={56}
                range1={getRunMin()}
                range2={getRunSecond()}
                unit1={Strings.getLang("str_minute_unit")}
                unit2={Strings.getLang("str_second_unit")}
                handlePickerChange={handleRunPickerChange}
                title={Strings.getLang("str_running_time")} current={runTime} />
            </View>
            <View className={styles.pickerTimer}>
              <TimePicker pickerwidth={'100%'}
                pickerheight={420}
                fontSize={36}
                indicatorheight={56}
                range1={getRunMin()}
                range2={getRunSecond()}
                unit1={Strings.getLang("str_minute_unit")}
                unit2={Strings.getLang("str_second_unit")}
                handlePickerChange={handlePausePickerChange}
                title={Strings.getLang("str_pause_duration")} current={pauseTime} />
            </View>
          </View>
        </View>
        <Text className={styles.saveBtn} onClick={save}>
          {Strings.getLang("str_save")}
        </Text>

      </View>

    </View>
  );
}

